/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.knowledgeBase;

import java.util.HashMap;
import java.util.Iterator;

public class UsedKeyword
{
	//Risk
	private static final double L01 = 1;
	private static final double L10 = 1;
	
	//Pi0 et Pi(1)
	private static double[][] Pi = new double[KnowledgeBaseAgent.LAST][2];
	
	//W0 pour chaque type de site
	private static double[] w0 = new double[KnowledgeBaseAgent.LAST];
	
	//Attributs de ce mot clé
	private String keyword;
	private double[] wj = new double[KnowledgeBaseAgent.LAST];
	double[][] probabilite;
	
	//Constructeur
	public UsedKeyword(String _keyword, double[][] _probabilite)
	{
		probabilite = _probabilite;
		keyword = _keyword;
		
		//Calcul des Wj
		for(int i = 0; i < KnowledgeBaseAgent.LAST; ++i)
		{
			if(probabilite[i][0] == 0) probabilite[i][0] = 0.0000001;
			else if(probabilite[i][0] == 1) probabilite[i][0] = 0.9999999;
			
			if(probabilite[i][1] == 0) probabilite[i][1] = 0.0000001;
			else if(probabilite[i][1] == 1) probabilite[i][1] = 0.9999999;
			
			wj[i] = Math.log(probabilite[i][0] / probabilite[i][1]) + Math.log( (1 - probabilite[i][1]) / (1 - probabilite[i][0]) );
		}
	}
	
	//Getters
	public String getName() { return keyword; }
	public double getWj(int websiteType) { return wj[websiteType]; }
	public static double getW0(int websiteType) { return w0[websiteType]; }
	
	//Calcul des Pi
	public static void computePi(int[] nbApprentissageWebsiteType, int nbTotalApprentissage)
	{
		for(int i = 0; i < KnowledgeBaseAgent.LAST; ++i)
		{
			Pi[i][1] = (double)nbApprentissageWebsiteType[i] / (double)nbTotalApprentissage;
			Pi[i][0] = 1 - Pi[i][1];
		}
	}
	
	//Calcul des W0
	public static void computeW0(HashMap<String, UsedKeyword> keywords)
	{
		Iterator<UsedKeyword> it = keywords.values().iterator();
		for(int i = 0; i < KnowledgeBaseAgent.LAST; ++i) w0[i] = 0;
		
		while(it.hasNext())
		{
			UsedKeyword current = it.next();
			for(int i = 0; i < KnowledgeBaseAgent.LAST; ++i)
				w0[i] += Math.log( (1 - current.probabilite[i][0]) / (1 - current.probabilite[i][1]) );
		}
		
		for(int i = 0; i < KnowledgeBaseAgent.LAST; ++i)
			w0[i] -= (Math.log(L01 / L10) + Math.log(Pi[i][1] / Pi[i][0]));
	}
}